package qeug.shsh.opplugin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.AppInfo;
import kd.bos.entity.AppMetadataCache;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.param.AppCustomParam;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.entity.validate.AbstractValidator;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.parameter.SystemParamServiceHelper;
import qeug.shsh.helper.FacadeHelper;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

import static qeug.shsh.helper.FacadeHelper.getSAPAPI;

public class MaterialCostExtOp extends AbstractOperationServicePlugIn {

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);
        List<AbstractValidator> validators = e.getValidators();
        // 删除标品校验器
//        validators.removeIf(validator -> validator instanceof PaymentMaxAmountValidator);
//        validators.removeIf(validator -> validator instanceof PaymentTypeValidator);
        // 添加定制二开的校验器（位置放第一位，优先执行）
        validators.add(0, new MaterialCostValidator());

    }


    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        try {
            QFilter[] q1 = new QFilter[]{new QFilter("qeug_issap", "=", true)};
            DynamicObject[] bosOrgs = BusinessDataServiceHelper.load("bos_org", "qeug_issap,id,number", q1);
            List<String> orgNum = new ArrayList();
            for (DynamicObject bosOrg : bosOrgs) {
                orgNum.add(bosOrg.getString("number"));
            }
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 获取当前年并转换为字符串
            String currentYear = String.valueOf(currentDate.getYear());
            // 获取当前月并转换为字符串，若为个位数则不显示前面的 0
            int monthValue = currentDate.getMonthValue();
            String currentMonth = String.valueOf(monthValue);
            String url = System.getProperty("sapacc.url");
            String basicAuthUserName = "ccsuser";
            HashMap<String, Object> log = new HashMap<>();
            log.put("operationModule", "手动抽取物料费用");
            log.put("url", url);
            log.put("user", basicAuthUserName);
            log.put("mode", "POST");
            log.put("action", "");

            log.put("opdate", new Date());
            //根据应用编码从缓存中获取应用信息
            AppInfo cgfwAppInfo = AppMetadataCache.getAppInfo("gl");
            //获取应用的主键
            String appId = cgfwAppInfo.getId();
            AppCustomParam appCustomParam = new AppCustomParam(appId);
            Map<String, String> cusTomMap = SystemParamServiceHelper.loadAppCustomParameterFromCache(appCustomParam);
            boolean isnull = true;
            int failCount = 0;
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < orgNum.size(); i++) {
                for (String value : cusTomMap.values()) {
                    String kjkm = value;
                    JSONObject body = new JSONObject();
                    body.put("BUKRS", orgNum.get(i));
                    body.put("GJAHR", currentYear);
                    body.put("MONAT", currentMonth);
                    body.put("RACCT", kjkm);
                    String sapapi = getSAPAPI(body.toJSONString(), url);
                    JSONArray voucher = FacadeHelper.getVoucher(sapapi);
                    if (voucher == null){
                        isnull = false;
                        continue;
                    }
                    String result = createVoucherStructure(voucher);
                    log.put("mainstring", body.toJSONString());
                    log.put("responsebody", sapapi);
                    JSONObject date = JSONObject.parseObject(result).getJSONObject("date");
                    failCount = failCount +Integer.parseInt(date.getString("failCount"));
                    if (failCount > 0) {
//                        log.put("pdesc", "失败");
//                        log.put("operating_mode", date.getJSONArray("result"));
//                        FacadeHelper.apiLog(log);
                        sb.append(date.getJSONArray("result"));
                    } else {
//                        log.put("pdesc", "成功");
//                        FacadeHelper.apiLog(log);
                    }
                }
            }
            if (isnull){
                sb.append(currentDate+"该日期下未查到数据");
            }
            if (failCount > 0) {
                        log.put("pdesc", "失败");
                        log.put("operating_mode", sb.toString());
                        FacadeHelper.apiLog(log);
            } else {
                        log.put("pdesc", "成功");
                        FacadeHelper.apiLog(log);
            }
        } catch (ParseException e1) {
            throw new RuntimeException(e1);
        } catch (IOException e1) {
            throw new RuntimeException(e1);
        }
    }

    public static String createVoucherStructure(JSONArray jsonArray) throws ParseException, IOException {
//        String voucher = sapService.getVoucher(body.toJSONString());
        JSONArray dataArray = new JSONArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            boolean isMater = false;
            DynamicObject materialCostBill = ORM.create().newDynamicObject("qeug_materialcostbill");
            JSONObject sapInfo = jsonArray.getJSONObject(i);
            String BUKRS = sapInfo.getString("BUKRS");//公司代码
            DynamicObject company = FacadeHelper.getDynamicObject("bos_org", "number", BUKRS);
            String GJAHR = sapInfo.getString("GJAHR");//年度
//            String GJAHR = "2024";//年度
            String MONAT = sapInfo.getString("MONAT");//期间
            DynamicObject period = FacadeHelper.getDynamicObject("bd_period", "number", GJAHR + MONAT);
            String BELNR = sapInfo.getString("BELNR");//凭证编号
            String BLDAT = sapInfo.getString("BLDAT");//业务日期
            materialCostBill.set("billno", BELNR + BUKRS + GJAHR);//单据编号
            materialCostBill.set("billstatus", "A");//单据状态
            materialCostBill.set("creator", BELNR + BUKRS + GJAHR);//创建人
            materialCostBill.set("org", company);//组织
            materialCostBill.set("qeug_billtype", FacadeHelper.getDynamicObject("bos_billtype", "number", "qeug_materialcostbill_wl"));//
            materialCostBill.set("qeug_bizdate", new SimpleDateFormat("yyyyMMdd").parse(BLDAT));//业务日期
            DynamicObjectCollection materialCostEntrys = materialCostBill.getDynamicObjectCollection("entryentity");
            JSONArray voucherItem = sapInfo.getJSONArray("items");
            JSONArray entriesArray = new JSONArray();
            for (int j = 0; j < voucherItem.size(); j++) {
                JSONObject voucherentry = voucherItem.getJSONObject(j);
                String RACCT = voucherentry.getString("RACCT");//科目代码
                DynamicObject accountview = FacadeHelper.getDynamicObject("bd_accountview", "qeug_sapnumber", RACCT);
//                DynamicObject accountview = FacadeHelper.getDynamicObject("bd_accountview", "number", "1221.02");
                String MATNR = voucherentry.getString("MATNR");//物料号
                String WSL = voucherentry.getString("WSL").trim();//以交易货币计的金额
                String DRCRK = voucherentry.getString("DRCRK");//借/贷标识
                String RCNTR = voucherentry.getString("RCNTR");//成本中心代码
                DynamicObject bos_costcenter = FacadeHelper.getDynamicObject("bos_costcenter", "number", RCNTR);
                DynamicObject expInfo = new DynamicObject();
                if (MATNR != null) {
                    isMater = true;
                    expInfo = getExpInfo(MATNR);
                    DynamicObject materialCostEntry = materialCostEntrys.addNew();
                    materialCostEntry.set("qeug_accountview", accountview);//会计科目
                    materialCostEntry.set("qeug_expenseitemedit", expInfo);//费用项目
                    materialCostEntry.set("qeug_costcenter", bos_costcenter);//成本中心
                    QFilter[] q1 = new QFilter[]{new QFilter("costcenter.number", "=", RCNTR)};
                    DynamicObject costcentersourcemap = BusinessDataServiceHelper.loadSingle("bos_costcentersourcemap", q1);
                    if (costcentersourcemap != null) {
                        DynamicObject org = costcentersourcemap.getDynamicObjectCollection("entryentity").get(0).getDynamicObject("sourcedata");
                        materialCostEntry.set("qeug_org", org);//费用承担部门
                    }
                    materialCostEntry.set("qeug_supplies", MATNR);//物料号
                    materialCostEntry.set("qeug_suppliesmean", "");//物料描述
                    materialCostEntry.set("qeug_jdtype", DRCRK);//借贷方向
                    materialCostEntry.set("qeug_amount", new BigDecimal(FacadeHelper.formatNumber(WSL)));//金额
                }
            }
            if (isMater) {
                OperationResult operationResult = SaveServiceHelper.saveOperate("qeug_materialcostbill", new DynamicObject[]{materialCostBill}, null);
                System.out.println(operationResult);
            }
        }
        return "";
    }

    public static DynamicObject getExpInfo(String matnr) {
        QFilter[] qFilters = new QFilter[]{new QFilter("qeug_suppliesnum", "=", matnr)};
        DynamicObject qeug_supplies_expense = BusinessDataServiceHelper.loadSingle("qeug_supplies_expense", qFilters);
        return qeug_supplies_expense.getDynamicObject("qeug_expense");
    }
}
